package com.opencee.cloud.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.opencee.boot.db.mybatis.service.impl.SupperServiceImpl;
import com.opencee.cloud.base.entity.BaseRoleEntity;
import com.opencee.cloud.base.entity.BaseRoleGrantedEntity;
import com.opencee.cloud.base.entity.BaseUserEntity;
import com.opencee.cloud.base.mapper.BaseRoleGrantedMapper;
import com.opencee.cloud.base.service.IBaseRoleGrantedService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yadu
 */
@Service
public class BaseRoleGrantedServiceImpl extends SupperServiceImpl<BaseRoleGrantedMapper, BaseRoleGrantedEntity> implements IBaseRoleGrantedService {

    /**
     * 清空用户授权
     *
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByUserId(Long userId) {
        QueryWrapper<BaseRoleGrantedEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseRoleGrantedEntity::getUserId, userId);
        return remove(wrapper);
    }

    /**
     * 清空角色授权
     *
     * @param roleId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByRoleId(Long roleId) {
        QueryWrapper<BaseRoleGrantedEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseRoleGrantedEntity::getRoleId, roleId);
        return remove(wrapper);
    }

    /**
     * 移除成员
     *
     * @param roleId
     * @param userIdSet
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeBy(Long roleId, Set<Long> userIdSet) {
        if (CollectionUtils.isEmpty(userIdSet)) {
            return false;
        }
        QueryWrapper<BaseRoleGrantedEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseRoleGrantedEntity::getRoleId, roleId)
                .in(BaseRoleGrantedEntity::getUserId, userIdSet);
        return remove(wrapper);
    }

    /**
     * 角色是否存在授权
     *
     * @param roleId
     * @return
     */
    @Override
    public boolean hasGranted(Long roleId) {
        QueryWrapper<BaseRoleGrantedEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseRoleGrantedEntity::getRoleId, roleId);
        return count(wrapper) > 0;
    }

    /**
     * 是否已授权
     *
     * @param roleId
     * @param userId
     * @return
     */
    @Override
    public boolean hasGranted(Long roleId, Long userId) {
        QueryWrapper<BaseRoleGrantedEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseRoleGrantedEntity::getRoleId, roleId)
                .eq(BaseRoleGrantedEntity::getUserId, userId);
        return count(wrapper) > 0;
    }

    /**
     * 用户授权角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void userSaveRoles(Long userId, Set<Long> roleIds) {
        // 清空已授权角色
        removeByUserId(userId);
        // 移除缓存
        List<BaseRoleGrantedEntity> entityList = roleIds.stream().map(t -> {
            BaseRoleGrantedEntity entity = new BaseRoleGrantedEntity();
            entity.setUserId(userId);
            entity.setRoleId(t);
            return entity;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(entityList)) {
            super.saveBatch(entityList);
        }
    }

    /**
     * 角色添加成员
     *
     * @param roleId
     * @param userSet
     */
    @Override
    public void addRoleUsers(Long roleId, Set<Long> userSet) {
        List<BaseRoleGrantedEntity> entityList = userSet.stream().filter(t -> !hasGranted(roleId, t)).map(t -> {
            BaseRoleGrantedEntity entity = new BaseRoleGrantedEntity();
            entity.setUserId(t);
            entity.setRoleId(roleId);
            return entity;
        }).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(entityList)) {
            super.saveBatch(entityList);
        }
    }

    /**
     * 成员添加角色
     *
     * @param userId
     * @param roleSet
     */
    @Override
    public void addUserRoles(Long userId, Set<Long> roleSet) {
        List<BaseRoleGrantedEntity> entityList = roleSet.stream().filter(t -> !hasGranted(t, userId)).map(t -> {
            BaseRoleGrantedEntity entity = new BaseRoleGrantedEntity();
            entity.setUserId(userId);
            entity.setRoleId(t);
            return entity;
        }).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(entityList)) {
            super.saveBatch(entityList);
        }
    }

    /**
     * 查询用户已授权角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<BaseRoleEntity> listRolesByUserId(Long userId) {
        return baseMapper.getRolesByUserId(userId);
    }

    /**
     * 根据id,批量查询角色成员列表
     *
     * @param roleId
     * @return
     */
    @Override
    public List<BaseUserEntity> listUsersByRoleId(Long roleId) {
        return baseMapper.getUsersByRoleId(roleId);
    }


}
